package com.apts.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;

/**
 * 图片验证码工具类
 * 
 * @author lwh
 * @date 2016-6-2
 */
public class ImgCode {

	// 验证码宽度
	private int width;
	// 验证码高度
	private int height;
	// 验证码字符总数
	private int codeCount;
	// 验证码干扰线总数
	private int lineCount;
	// 随机类
	Random random = new Random();
	// 验证码
	private String code = null;
	// 图片验证码输入流
	private InputStream inputStream = null;
	// 内存图片
	private BufferedImage bufferImg = null;

	private ImgCode() {
	}

	public static ImgCode create() {
		return new ImgCode();
	}

	/**
	 * 初始化图片验证码工具类
	 * 
	 * @param width
	 *            验证码宽度
	 * @param height
	 *            验证码高度
	 * @param codeCount
	 *            验证码字符数量
	 * @param lineCount
	 *            干扰线数量
	 * @return ImageCodeUtil
	 * @throws IOException
	 */
	public ImgCode init(int width, int height, int codeCount, int lineCount) {
		this.width = width;
		this.height = height;
		this.codeCount = codeCount;
		this.lineCount = lineCount;
		this.code = this.createCode(this.codeCount);
		this.inputStream = this
				.imageToInputStream(this.createBufferImage(this.width, this.height, this.lineCount, this.code));
		return this;
	}

	/**
	 * 获取验证码字符串
	 * 
	 * @return
	 */
	public String getCode() {
		return this.code.toLowerCase();
	}

	/**
	 * 获取图片验证码输入流
	 * 
	 * @return
	 */
	public InputStream getInputStream() {
		return this.inputStream;
	}

	/**
	 * 获取内存图片对象
	 * 
	 * @return
	 */
	public BufferedImage getBufferedImage() {
		return this.bufferImg;
	}

	/**
	 * 缓存图片转化为输入流
	 * 
	 * @param image
	 * @return
	 */
	private InputStream imageToInputStream(BufferedImage image) {
		// 创建储存图片二进制流的输出流
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		// 创建ImageOutputStream流
		ImageOutputStream imageOutputStream = null;
		InputStream inputStream = null;
		try {
			imageOutputStream = ImageIO.createImageOutputStream(baos);
			// 将二进制数据写进ByteArrayOutputStream
			ImageIO.write(image, "jpg", imageOutputStream);
			inputStream = new ByteArrayInputStream(baos.toByteArray());
		} catch (IOException e) {
			e.printStackTrace();
		}
		return inputStream;
	}

	/**
	 * 创建验证码缓存图片
	 * 
	 * @param width
	 * @param height
	 * @param lineCount
	 * @param code
	 * @return
	 * @throws IOException
	 */
	private BufferedImage createBufferImage(int width, int height, int lineCount, String code) {
		bufferImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics g = bufferImg.getGraphics();
		// 画背景图/色
		this.drawBackground(g, null, width, height);
		// 画干扰线
		// this.drawLine(g, lineCount);
		// 画噪点
		// this.drawPoint(g, 0.002);
		// 画字符
		this.drawString(g);
		g.dispose();
		return bufferImg;
	}

	/**
	 * 创建验证码字符串
	 * 
	 * @param codeCount
	 * @return string
	 */
	private String createCode(int codeCount) {
		String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890abcdefghijklmnopqrstuvwxyz";
		StringBuffer strb = new StringBuffer();
		for (int i = 0; i < codeCount; i++) {
			strb.append(str.charAt(random.nextInt(str.length())));
		}
		return strb.toString();
	}

	/**
	 * 画字符
	 * 
	 * @param g
	 */
	private void drawString(Graphics g) {
		// 画验证码字符串
		int fontWidth = width / codeCount;
		int fontHeight = (int) (height * 0.45);
		for (int i = 0; i < codeCount; i++) {
			String charStr = code.substring(i, i + 1);
			int fontsize = fontWidth;
			g.setFont(getFont(fontsize));
			// g.drawString(a,x,y);
			// a为要画出来的东西，x和y表示要画的东西最左侧字符的基线位于此图形上下文坐标系的 (x, y) 位置处，居中算法
			int x = i * fontWidth + ((int)(fontWidth*1.10) - fontsize);
			int y = fontHeight + (int) ((height - fontHeight) * 0.5);
			g.setColor(getRandColor(0, 255));
			g.drawString(charStr, x, y);
		}
	}

	/**
	 * 产生随机字体
	 * 
	 * @param size
	 * @return
	 */
	private Font getFont(int size) {
		Random random = new Random();
		Font font[] = new Font[5];
		font[0] = new Font("Ravie", Font.BOLD, size);
		font[1] = new Font("Antique Olive Compact", Font.BOLD, size);
		font[2] = new Font("Fixedsys", Font.BOLD, size);
		font[3] = new Font("Wide Latin", Font.BOLD, size);
		font[4] = new Font("Gill Sans Ultra Bold", Font.BOLD, size);
		return font[random.nextInt(5)];
	}

	/**
	 * 得到随机颜色
	 * 
	 * @param begin
	 * @param end
	 * @return
	 */
	private Color getRandColor(int begin, int end) {// 给定范围获得随机颜色
		if (begin > 255) {
			begin = 255;
		}
		if (begin < 0) {
			begin = 0;
		}
		if (end > 255) {
			end = 255;
		}
		if (end < 0) {
			end = 0;
		}
		int r = begin + random.nextInt(end - begin);
		int g = begin + random.nextInt(end - begin);
		int b = begin + random.nextInt(end - begin);
		return new Color(r, g, b);
	}

	/**
	 * 设置背景图片
	 * 
	 * @author lwh
	 * @param g
	 * @param width
	 *            图宽
	 * @param height
	 *            图高
	 * @throws IOException
	 * @date 2016-03-20
	 */
	private void drawBackground(Graphics g, File bgimg, int width, int height) {
		if (bgimg == null) {
			Color _color = g.getColor();
			g.setColor(new Color(221, 221, 221)); //设置画笔颜色
			g.fillRect(0, 0, width, height);//这里填充背景颜色
			g.setColor(_color);
		} else {
			Image codeimg = null;
			try {
				codeimg = ImageIO.read(bgimg);
			} catch (IOException e) {
				e.printStackTrace();
			}
			g.drawImage(codeimg, 0, 0, width, height, null);
		}
	}

}
